import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:pretty_dio_logger/pretty_dio_logger.dart';
import 'package:x_builder/base/network/interceptor/data_encryption_interceptor.dart';
import 'package:x_builder/base/network/model/device_type.dart';
import 'package:x_builder/base/network/model/http_constants.dart';

class DioClient {
  static final DioClient _instance = DioClient._();

  final Dio _dio;

  DioClient._()
      : _dio = Dio(BaseOptions(
          baseUrl: HttpConstants.baseUrl,
          headers: _buildHeaders(),
          connectTimeout: const Duration(seconds: 5),
          receiveTimeout: const Duration(seconds: 5),
          responseType: ResponseType.json,
        )) {
    _addInterceptors();
  }

  static DioClient get instance => _instance;

  Dio get dio => _dio;

  static Map<String, String> _buildHeaders() {
    return {
      HttpConstants.contentType: HttpConstants.applicationJson,
      HttpConstants.accept: HttpConstants.applicationJson,
      HttpConstants.token: "",
      HttpConstants.userId: "",
      HttpConstants.hardware: DeviceType.android.name,
    };
  }

  void _addInterceptors() {
    if (!kReleaseMode) {
      _dio.interceptors.add(PrettyDioLogger(
        requestHeader: true,
        requestBody: true,
        responseHeader: true,
        responseBody: true
      ));
    }
    _dio.interceptors.add(DataEncryptionInterceptor());
  }

  void addInterceptor(Interceptor interceptor) {
    _dio.interceptors.add(interceptor);
  }
}
